package net.hctek.identity.action;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.commons.io.FileUtils;


import com.opensymphony.xwork2.ActionSupport;

import net.hctek.identity.bean.Files;
import net.hctek.identity.bean.User;
import net.hctek.identity.service.IdentityServiceI;
import net.hctek.identity.util.Contant;

public class FileUploadAction extends ActionSupport {

	private static final long serialVersionUID = 1L;
	
	private List<File> upload;
	private List<String> uploadFileName;
	private String tip;
	
	@Autowired
	private IdentityServiceI identityService;
	
	@Override
	public String execute(){
		Files files = new Files();
		List<String> temp = new ArrayList<>();
		Set<User> users = new HashSet<>();
		List<String> filePaths = new ArrayList<>();
		List<Files> filess = new ArrayList<>();
		
		
		User u = (User)ServletActionContext.getRequest().getSession().getAttribute(Contant.SESSION_USER);
		if(u != null){
			users.add(u);
			
			String filePath = ServletActionContext.getServletContext().getRealPath("/upload/"+"Musiclibrary");
			
			File file = new File(filePath);
			if(!file.exists()){
				file.mkdirs();
			}
			try {
				for(int i=0;i<upload.size();i++){
					
						filePaths.add(i,filePath+"\\"+uploadFileName.get(i).toString());
						temp = identityService.Duplicatefiles("MusicLibrary",uploadFileName.get(i));
						System.out.println("temp:"+temp);
						if(!temp.toString().equals("[]")){
							tip = "警告:你上传的文件名:"+uploadFileName.get(i)+"已重复,文件已替换新";
						}else{
							files.setUploadFileName(uploadFileName.get(i));
							files.setFilepath(filePaths.get(i));
							files.setUsers(users);
							filess.add(files);
							identityService.savaFiles(filess);
							tip = "上传成功";
						}
						FileUtils.copyFile(upload.get(i), new File(file,uploadFileName.get(i)));	
				}
			} catch (Exception e) {
				e.printStackTrace();
				tip="上传失败";
			}
		}else{
			tip="请登录";
		}
		ServletActionContext.getResponse().setCharacterEncoding("UTF-8");
		
		try {
			ServletActionContext.getResponse().getWriter().print(tip);
		} catch (IOException e) { 
			e.printStackTrace();
		}
		return NONE;
	}
	
	public List<File> getUpload() {
		return upload;
	}
	public void setUpload(List<File> upload) {
		this.upload = upload;
	}
	public List<String> getUploadFileName() {
		return uploadFileName;
	}
	public void setUploadFileName(List<String> uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
	public String getTip() {
		return tip;
	}
	public void setTip(String tip) {
		this.tip = tip;
	}

	
	

}
